package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"learn_beego/models"
)

type UserController struct {
	baseController
}

func (c *UserController) Save() {
	user := models.User{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &user); err != nil {
		c.respErr("Unmarshal err" + err.Error())
	}
	switch user.Id {
	case 0:
		if _, err := orm.NewOrm().Insert(&user); err != nil {
			c.respErr("Insert err" + err.Error())
		} else {
			c.resp("Insert successfully")
		}
	default:
		if _, err := orm.NewOrm().Update(&user); err != nil {
			c.respErr("Update err" + err.Error())
		} else {
			c.resp("Update successfully")
		}
	}
}
func (c *UserController) QueryByName() {
	name := c.GetString("name")
	var users []*models.User
	orm.NewOrm().QueryTable(new(models.User).TableName()).Filter("name", name).All(&users)
	c.resp(&users)
}

func (c *UserController) QueryByPage() {
	PageReq := models.PageReq{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &PageReq); err != nil {
		c.respErr("Unmarshal err" + err.Error())
	}
	var users []*models.User
	o := orm.NewOrm()
	count, err := o.QueryTable(new(models.User)).Filter("name", PageReq.Name).Count()
	if err != nil {
		c.respErr("QueryByPage error" + err.Error())
	}
	totalPage, offset, currentPage := models.PageCount(count, PageReq.PageSize, PageReq.Page)
	_, err = o.QueryTable(new(models.User)).Filter("name", PageReq.Name).Limit(PageReq.PageSize, offset).All(&users)
	pager := models.Pager{
		Count:       count,
		CurrentPage: currentPage,
		Data:        users,
		PageSize:    PageReq.PageSize,
		TotalPages:  totalPage,
	}
	c.resp(&pager)
}
